object ComplexWordCount {
  def main(args: Array[String]): Unit = {

    /**
     * 7.7.6 复杂WordCount案例
     * 1）方式一
     * */
    // 第一种方式（不通用）
    val tupleList = List(("Hello Scala Spark World", 4), ("Hello Scala Spark", 3), ("Hello Scala", 2), ("Hello", 1))

    val stringList: List[String] = tupleList.map(element => (element._1 + " ") * element._2)
    println(stringList)

    //val words: List[String] = stringList.flatMap(s => s.split(" "))
    val words: List[String] = stringList.flatMap(_.split(" "))
    println(words)

    //在map中，如果传进来什么就返回什么，不要用_省略
    val groupMap: Map[String, List[String]] = words.groupBy(word => word)
    println(groupMap)
    //val groupMap: Map[String, List[String]] = words.groupBy(_)

    // (word, list) => (word, count)
    val wordToCount: Map[String, Int] = groupMap.map(t => (t._1, t._2.size))
    println(wordToCount)

    // 排序并取前三 -- 自定义排序规则
    val wordCountList: List[(String, Int)] = wordToCount.toList.sortWith {
      (head, tail) => {
        head._2 > tail._2
      }
    }.take(3)

    //tupleList.map(t=>(t._1 + " ") * t._2).flatMap(_.split(" ")).groupBy(word=>word).map(t=>(t._1, t._2.size))
    for (elem <- wordCountList) {
      println(elem)
    }
    println(wordCountList)

    /** 2）方式二 */
    val tuples = List(("Hello Scala Spark World", 4), ("Hello Scala Spark", 3), ("Hello Scala", 2), ("Hello", 1))
    // (Hello,4),(Scala,4),(Spark,4),(World,4)
    // (Hello,3),(Scala,3),(Spark,3)
    // (Hello,2),(Scala,2)
    // (Hello,1)
    val wordToCountList: List[(String, Int)] = tuples.flatMap {
      t => {
        val strings: Array[String] = t._1.split(" ")
        println(strings.mkString("Array(", ", ", ")"))
        // 转化/映射
        strings.map(word => (word, t._2))
      }
    }
    println(wordToCountList)

    // Hello, List((Hello,4), (Hello,3), (Hello,2), (Hello,1))
    // Scala, List((Scala,4), (Scala,3), (Scala,2)
    // Spark, List((Spark,4), (Spark,3)
    // Word, List((Word,4))
    // 分组操作
    val wordToTupleMap: Map[String, List[(String, Int)]] = wordToCountList.groupBy(t => t._1)
    println(wordToTupleMap)

    //    // 聚合取值操作 将map的value的第二位取出来得到 ：
    //    // Map(Hello -> List(4, 3, 2, 1), Spark -> List(4, 3), Scala -> List(4, 3, 2), World -> List(4))
    //    val stringToInts: Map[String, List[Int]] = wordToTupleMap.mapValues {
    //      data => data.map(t => t._2)
    //    }
    //    println(stringToInts)

    // 求值操作 将map中的value的第二位值取出相加
    val wordToCountMap: Map[String, List[Int]] = wordToTupleMap.map {
      t => {
        (t._1, t._2.map(t1 => t1._2))
      }
    }
    println(wordToCountMap)
    val wordToTotalCountMap: Map[String, Int] = wordToCountMap.map(t => (t._1, t._2.sum))
    println(wordToTotalCountMap)
  }
}
